package com.xtaller.sdboot.util;

import com.alibaba.fastjson.JSONObject;
import com.xtaller.sdboot.utils.helper.JsonHelper;
import com.xtaller.sdboot.utils.helper.LocalHelper;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author : Taller
 * @date : 2020/2/28 00:30
 * @Description : 缓存工具
 */
@Component
public class CacheUtil {
    @Autowired private RedisUtil redisUtil;
    @Value("${customize.cache.is-redis}")
    private boolean IS_REDIS;

    public void delete(String key){
        if(IS_REDIS){
            redisUtil.delete(key);
        }else {
            LocalHelper.clear(key);
        }
    }

    /**
     * 设置缓存
     * @param expire 单位秒
     * */
    public void set(String key, Object object, int expire){
        if(IS_REDIS){
            redisUtil.set(key, object, expire);
        }else {
            LocalHelper.set(key, object, expire);
        }
    }
    public void set(String key, Object object){
        this.set(key, object, -1);
    }
    /**
     * 读取缓存
     * */
    public Object get(String key){
        if(IS_REDIS){
            return redisUtil.get(key);
        }else {
            return LocalHelper.get(key);
        }
    }
    public <T> T get(String key, Class<T> cls){
        var object = get(key);
        if(object != null){
            return JsonHelper.s2m(object.toString(), cls);
        }
        return null;
    }
    public List<JSONObject> getList(String key){
        var object = get(key);
        if(object != null){
            return JsonHelper.s2l(object.toString());
        }
        return null;
    }
    public <T> List<T> getList(String key, Class<T> cls){
        var object = get(key);
        if(object != null){
            return JsonHelper.parseArray(object.toString(), cls);
        }
        return null;
    }
    public String getString(String key){
        var object = get(key);
        if(object != null){
            return object.toString();
        }
        return null;
    }

    public void clear(String key) {
        LocalHelper.clear(key);
    }

}
